package com.sfdk.admin.helpers
{
	import com.sfdk.admin.data.api.IDataSource;
	import com.sfdk.admin.structure.TreeNode;
import com.sfdk.data.api.ITreeDataProvider;

import mx.collections.ArrayCollection;
	import mx.collections.IList;

	public class TreeNodeFactory
	{
		public static function buildTreeNodeCollection(dataSource : IDataSource) : TreeNode
		{
			var currentTreeInfo : ITreeDataProvider;
			var repertoire : Array;

			var rootNode : TreeNode = new TreeNode("root");
			var currentNode : TreeNode;
			var tempNode : TreeNode;
			var found : Boolean;
			var i : int, j : int;
			var initData : IList = dataSource.data;
			for(i = 0; i < initData.length; i++)
			{
				found = false;
				currentTreeInfo = initData[i] as ITreeDataProvider;
				repertoire = currentTreeInfo.fullName.split("/");
				currentNode = rootNode;
				
				for(j = 1; j < (repertoire.length - 1); j++)
				{
					tempNode = currentNode.getChildByName(repertoire[j]) as TreeNode;
					if(tempNode == null)
					{
						tempNode = new TreeNode(repertoire[j]);
						currentNode.addChild(tempNode);
					}
					currentNode = tempNode;
				}
				
				tempNode = new TreeNode(repertoire[j]);
				tempNode.bindData(currentTreeInfo);
				currentNode.addChild(tempNode);
			}
			return rootNode;
		}
	}
}